package com.atzzy.ysmall.ysmall_api.interceptor;

import com.atzzy.ysmall.ysmall_common.vo.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author JAVAZeng
 * @Date 2022/3/1 17:32
 * @Version 1.0
 */
@Component
//设置拦截器
public class CheckTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
if("OPTIONS".equalsIgnoreCase(method))
{
    return true;
}
        String token = request.getHeader("token");
        if (token == null) {
            R result = new R(502, "请先登录", null);
            doResponse(response, result);
            //提示登录
            return false;
        } else {
            try {
                //验证token
                JwtParser parser = Jwts.parser();
                parser.setSigningKey("zzyYYDS");//解析
                //如果token正确 (密码正确 //有效期内 正常执行) 否则抛出异常
                Jws<Claims> claimsJws = parser.parseClaimsJws(token);
                return true;
            } catch (ExpiredJwtException e) {
                R result = new R(602, "登录过期 请重新登录", null);
                doResponse(response, result);


            } catch (UnsupportedJwtException e) {

                R result = new R(702, "Token不合法", null);
                doResponse(response, result);

            } catch (Exception e) {
                R result = new R(502, "请先登录", null);
                doResponse(response, result);
            }
            return false;
        }
    }

    private void doResponse(HttpServletResponse response, R result) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String s = new ObjectMapper().writeValueAsString(result);
        out.println(s);
        out.flush();
        out.close();
    }
}
